package com.powernode.controller;

import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.crypto.digest.DigestUtil;
import com.powernode.common.Result;
import com.powernode.constants.CoreConstant;
import com.powernode.domain.SysUser;
import com.powernode.enums.ResultEnums;
import com.powernode.service.SysUserService;
import com.powernode.utils.ServletUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class LoginController extends BaseController{

    @Resource
    private SysUserService sysUserService;

    /**
     * 登录方法
     */
    @PostMapping("login")
    public Result<?> login(String username,String password,String code ){
        //从session里面取出验证码对象
        CircleCaptcha captcha = (CircleCaptcha) ServletUtils.getSession().getAttribute(CoreConstant.CAPTCHA_KEY);

        if (captcha==null){
            return new Result<>(ResultEnums.ERROR,"验证码未生成!!!");
        }
        if (!captcha.verify(code)){
            return new Result<>(ResultEnums.ERROR,"验证码错误！！！");
        }
        SysUser sysUser=sysUserService.login(username, DigestUtil.md5Hex(password));

        if (sysUser==null){
            return new Result<>(ResultEnums.ERROR,"用户名或密码错误");
        }
        ServletUtils.getSession().setAttribute(CoreConstant.SESSION_KEY,sysUser);
        return new Result<>(ResultEnums.SUCCESS.getCode(),"登陆成功",sysUser);
    }

    /**
     * 获取用户数据
     */
    @GetMapping("getUserInfo")
    public Result<?> getUserInfo(){
        //查询所有权限
        SysUser sysUser = (SysUser) ServletUtils.getSession().getAttribute(CoreConstant.SESSION_KEY);
        Map<String,Object> data=new HashMap<>();
        sysUser.setPassword("");
        data.put(CoreConstant.SESSION_KEY,sysUser);
        List<String> permissions=null;
        if (sysUser.getUserType().equals(CoreConstant.USER_TYPE_ADMIN)){
            //超级管理员
            permissions=sysUserService.queryAllPermissions();
        }else {
            //普通用户
            permissions=sysUserService.queryUserPermissionsByUserId(sysUser.getUserId());
        }
        data.put(CoreConstant.PERMISSIONS_KEY,permissions);
        return new Result<>(ResultEnums.SUCCESS,data);
    }

    /**
     * 退出登录
     */
    @GetMapping("logout")
    public Result logout(){
        ServletUtils.getSession().invalidate();//让session失效
        return new Result();
    }
}
